package com.samp.solr.update;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;

/**
 * solr有三种commit方式，hand,soft,commitWithIn.
 */
public class SolrCommitDemo {

    private final static String SOLR_URL = "http://localhost:8080/solr/samp";

    /**
     * commit是硬提交，commit后马上可以查询.
     * 如果没有commit,只有add，不会提交，数据会丢失。
     * 如果用solr.add(document, 10)，则在10s内会提交，测试是1s后
     * solr.commit(true,true,true);软提交后，基本也是1s后就会查到。
     * 配置autoSoftCommit不为-1时，直接add，到了指定时间就会提交，也会查询得到，solr.add的数据也不会丢失。
     */
    private static void commit(String id) throws Exception{
        HttpSolrClient solr = new HttpSolrClient.Builder(SOLR_URL).build();
        SolrInputDocument document = new SolrInputDocument();
        document.addField("id", id);
        document.addField("cat", "硬提交");
        solr.add(document);
//        solr.add(document, 10);
//        solr.commit();
//        solr.commit(true,true,true);
    }

    private static void queryById(String id) throws Exception{
        HttpSolrClient solrclient =  new HttpSolrClient.Builder(SOLR_URL).build();
        SolrQuery query = new SolrQuery();
        query.add("defType","edismax");
        query.set("q","id:"+id);
        QueryResponse response = solrclient.query(query);
        Long numFound = response.getResults().getNumFound();
        System.out.println("id:"+id+", found:"+numFound);
    }

    public static void main(String[] args) {
        try{
            String id = "100003";
            queryById(id);
            commit(id);
            int i = 1 ;
            while ( i > 0 ){
                queryById(id);
                Thread.sleep(1000);
                i--;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
